const query = require("../extend/query");

const getUserList = async (param) => {
  let sql = `select * from user`;
  let results = await query(sql);
  if (results.length > 0) {
    return {
      code: 200,
      message: "success",
      data: results,
    };
  } else {
    return {
      code: 400,
      message: "success",
      data: [],
    };
  }
};

// 订单列表
const gettrainList = async (param) => {
  let sql = `select * from orderdingdan`;
  let results = await query(sql);
  if (results.length > 0) {
    return {
      code: 200,
      message: "订单列表调用成功",
      data: results,
    };
  } else {
    return {
      code: 400,
      message: "订单列表调用失败",
      data: [],
    };
  }
};

// 删除订单
const deleteList = async ({ id }) => {
  let sql = `delete from orderdingdan where id=${id}`;
  let results = await query(sql);
  if (results.affectedRows) {
    return {
      code: 200,
      message: "订单列表id删除成功",
    };
  } else {
    return {
      code: 400,
      message: "订单列表id删除失败",
    };
  }
};

// 登录
const loginList = async ({ username, password }) => {
  console.log("username", username);
  console.log("password", password);
  let sql = `select * from user where username like '${username}' and password like '${password}'`;
  let results = await query(sql);
  if (results.length) {
    return {
      code: 200,
      message: "登录成功",
      key: 200,
    };
  } else {
    return {
      code: 400,
      message: "登录失败, 请检查用户名或密码",
    };
  }
};

// 注册
const righzhuce = async ({
  username,
  password,
  nickname,
  avatar,
  age,
  phone,
  email,
}) => {
  console.log("username", username);
  console.log("password", password);
  let sql = `select * from user where username like '${username}'`;
  let results = await query(sql);
  if (results.length) {
    return {
      code: 400,
      message: "该用户名已被使用， 请换个用户名",
    };
  } else {
    // 注册
    let sql = `insert into user (username, password, nickname, avatar, age, phone, email ) value ('${username}', ${password}, '${nickname}', '${avatar}', ${age}, ${phone}, ${email})`;
    let results = await query(sql);
    if (results.affectedRows) {
      return {
        code: 200,
        message: "注册成功",
      };
    } else {
      return {
        code: 400,
        message: "注册失败",
      };
    }
  }
};

module.exports = {
  getUserList,
  gettrainList,
  deleteList,
  loginList,
  righzhuce,
};
